
//
//  UIImage+extension.swift
//  新浪微博练习
//
//  Created by 韩旭 on 16/11/28.
//  Copyright © 2016年 韩旭. All rights reserved.
//

import UIKit

extension UIImage {
    
    /// 绘制图像
    ///
    /// - Parameters:
    ///   - isCornored: 是否是圆角
    ///   - size: 绘制的大小
    ///   - backgroundcolor: 背景颜色
       func wb_createImage(isCornored: Bool = true, size: CGSize = CGSize.zero, backgroundcolor: UIColor = UIColor.white) -> UIImage {
        
        //1.开启上下文
        UIGraphicsBeginImageContext(size)
        
        //2,设置填充颜色
        backgroundcolor.setFill()
        //3.颜色填充
        let rect = CGRect(origin: CGPoint.zero, size: size)
        UIRectFill(rect)
        //图像绘制
        let path = UIBezierPath(ovalIn: rect)
        path.addClip()
        self.draw(in: rect)
        //4.获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        //5.关闭上下文
        UIGraphicsEndImageContext()
 
        return image!
        
    }


/// 绘制图像
///
/// - Parameters:
///   - isCornored: 是否是圆角
///   - size: 绘制的大小
///   - backgroundcolor: 背景颜色
    func wb_asyncCreateImage(isCornored: Bool = true, size: CGSize = CGSize.zero, backgroundcolor: UIColor = UIColor.white, callBack:@escaping (_ image: UIImage)->())  {
        DispatchQueue.global().async {
            
            //1.开启上下文
            UIGraphicsBeginImageContext(size)
            
            //2,设置填充颜色
            backgroundcolor.setFill()
            //3.颜色填充
            let rect = CGRect(origin: CGPoint.zero, size: size)
            UIRectFill(rect)
            //图像绘制
            let path = UIBezierPath(ovalIn: rect)
            path.addClip()
            self.draw(in: rect)
            //4.获取图片
            let image = UIGraphicsGetImageFromCurrentImageContext()
            
            //5.关闭上下文
            UIGraphicsEndImageContext()
            
            DispatchQueue.main.async(execute: { 
                callBack(image!)
            })
        }
   }
}

